package site.fantasycube.blog.config.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.sun.istack.internal.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import site.fantasycube.blog.util.redis.IRedisCache;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author32172
 * @since2021/12/25
 * 配置拦截器
 */
@Component
public class SecuretyIntertor implements HandlerInterceptor{

    private IRedisCache redisCache;
    private static Logger logger = Logger.getLogger(SecuretyIntertor.class);
    @Autowired
    public void setRedisCache(IRedisCache redisCache){
        this.redisCache = redisCache;
    }

    /**
     *描述：请求进入方法前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求地址
        String uri = request.getRequestURI();
        //请求方式
        String method = request.getMethod();
        if (uri.indexOf(".out") != -1 || uri.indexOf("error") != -1 ){
            return true;
        }
        //获取cookie&token
        String token = request.getHeader("U-Token");
        logger.info(uri);
        //判断是否登录
        if (ObjectUtil.isNull(token)){
            //设置发送json格式的数据
            response.setContentType("application/json;charset=utf-8");
            //设置中文编码
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            //写入一个json对象
            writer.write("{\"success\":false,\"message\":\"nologin\"}");
            writer.flush();
            writer.close();
            return false;
        }
        Object userInfo = redisCache.getHash("login", token);
        if (ObjectUtil.isNotNull(userInfo)){
            redisCache.setOutTime(token,30L);
        }
        System.out.println("拦截器执行------>");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
